﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Alti.SharePoint.SPDataGenerator.Views;
using Alti.SharePoint.SPDataGenerator.Models;

namespace Alti.SharePoint.SPDataGenerator.Presenters
{
    public class SPDataGeneratorPresenter
    {
        ISPDataGeneratorView currentView;

        public SPDataGeneratorPresenter(ISPDataGeneratorView view)
        {
            currentView = view;
            currentView.IsSiteDataLoaded = false;
            currentView.IsSiteDataLoading = false;
        }

        public void LoadSiteDataAsync()
        {
            currentView.IsSiteDataLoaded = false;
            currentView.IsSiteDataLoading = true;

            System.ComponentModel.BackgroundWorker LoadDataBGW = new System.ComponentModel.BackgroundWorker();
            LoadDataBGW.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadDataBGW_DoWork);
            LoadDataBGW.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(LoadDataBGW_RunWorkerCompleted);

            LoadDataBGW.RunWorkerAsync();
        }

        void LoadDataBGW_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            LoadDataResult result = e.Result as LoadDataResult;
            if (result.ex != null)
                currentView.ShowError(result.ex);
            else
            {
                currentView.BindWebContentTypes(result.CTs);
                currentView.BindWebLists(result.Lists);

                currentView.IsSiteDataLoaded = true;
            }
            currentView.IsSiteDataLoading = false;
        }

        void LoadDataBGW_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            LoadDataResult result = new LoadDataResult();
            try
            {
                result.CTs = SharePointService.GetContentTypes(currentView.WebUrl);
                result.Lists = SharePointService.GetLists(currentView.WebUrl);
            }
            catch (Exception ex)
            {
                result.ex = ex;
            }
            
            e.Result = result;
        }

        public class LoadDataResult
        {
            public List<SPDataContentType> CTs;
            public List<SPDataList> Lists;
            public Exception ex = null;
        }


        public void GenerateSPDataClass()
        {
            string returnString = Helper.SPDataClassWriter.GenerateSPDataClass(currentView.GetListsToInclude(),
                currentView.GetContentTypesToInclude(),
                currentView.DestinationNamespace,
                currentView.IsHiddenFieldInclude);

            currentView.WriteOutputSPData(returnString);
        }

    }
}
